

import 'package:erp/Entity/PurchaseOrder.dart';
import 'package:erp/Events/EventAddrs.dart';
import 'package:erp/Store/AccountStore.dart';
import 'package:erp/Store/ProductsInWareHouseStore.dart';
import 'package:erp/Store/PurchaseStore.dart';
import 'package:erp/global.dart';

void registerPurchaseEvents(){
  globalBus.subscribe(Events.PURCHASE_SELECT_REQUEST, (bus, _) async {
    try {
      var count = await externalInterface.getAllPurchaseOrderCount(AccountStore.signInResult.token);

      var allOrders = List<PurchaseOrder>();
      for (var pageIndex = 0; pageIndex < count.allPageCount; pageIndex++){
        var orders = await externalInterface.getPurchaseOrders(AccountStore.signInResult.token);
        allOrders.addAll(orders);
      }
      PurchaseStore.purchaseOrders = allOrders;
      globalBus.publish(Events.PURCHASE_SELECT_SUCCESS, allOrders);
    }
    catch (exception){
      globalBus.publish(Events.PURCHASE_SELECT_ERROR, exception);
    }
  });

  globalBus.subscribe<PurchaseOrder>(Events.PURCHASE_INSERT_REQUEST, (bus, data) async {
    try {
      var result = await externalInterface.addPurchaseOrder(AccountStore.signInResult.token, data);
      PurchaseStore.purchaseOrders.add(result);
      globalBus.publish(Events.PURCHASE_INSERT_SUCCESS, result);
    }
    catch (exception){
      globalBus.publish(Events.PURCHASE_INSERT_ERROR, exception);
    }
  });

}



